/*
 * ClipArea.cpp
 *
 *  Created on: 11-12-2010
 *      Author: Piotr
 */

#include "gui/ClipArea.hpp"
#include "utils/MathUtils.hpp"
#include "pch.hpp"

geometry::Rectangle ClipArea::rootClip = geometry::Rectangle();

ClipArea::ClipArea() :
	xShift(0.0f), yShift(0.0f)
{
}

ClipArea::ClipArea(const geometry::Rectangle& clip, float xShift, float yShift) :
	clip(clip), xShift(xShift), yShift(yShift)
{

}

ClipArea::ClipArea(const ClipArea& clipArea) :
	clip(clipArea.clip), xShift(clipArea.xShift), yShift(clipArea.yShift)
{

}

ClipArea::~ClipArea()
{

}

void ClipArea::shift(const Vector& shiftVec)
{
	this->xShift += shiftVec.getX();
	this->yShift += shiftVec.getY();
}

float ClipArea::getX() const
{
	return clip.getPosition().getX();
}

float ClipArea::getY() const
{
	return clip.getPosition().getY();
}

float ClipArea::getWidth() const
{
	return clip.getSize().getWidth();
}

float ClipArea::getHeight() const
{
	return clip.getSize().getHeight();
}

ClipArea ClipArea::getUpdatedByControl(const Control& control) const
{
	const geometry::Rectangle& localArea = clip;
	const geometry::Rectangle& controlBounds = geometry::Rectangle(Vector(xShift
			+ control.getPosition().getX(), yShift + control.getPosition().getY()), control.getSize());

	geometry::Rectangle intersection = localArea.getIntersection(controlBounds);
	if(intersection.isEmpty())
	{
		return ClipArea();
	}

	return ClipArea(intersection, controlBounds.getPosition().getX(),
			controlBounds.getPosition().getY());
}

void ClipArea::setGLClipArea() const
{
	if(MathUtils::isNearZero(getWidth()) || MathUtils::isNearZero(getHeight()))
	{
		glScissor(0, 0, 0, 0);
	}
	else
	{
		int x0 = static_cast<int> (getX());
		int y0 = static_cast<int> (rootClip.getSize().getHeight() - getY() - getHeight());
		int x1 = static_cast<int> (getWidth());
		int y1 = static_cast<int> (getHeight());
		glScissor(x0, y0, x1, y1);
	}
}

